"""
@Author: li
@Email: lijianqiao2906@live.com
@FileName: role.py
@DateTime: 2025/07/06
@Docs: 角色管理相关API
"""

from typing import cast

from fastapi import APIRouter, Depends, HTTPException

from app.models import Role
from app.schemas.base import PaginatedResponse
from app.schemas.role import RoleCreate, RoleRead, RoleUpdate
from app.services.system import role_service
from app.utils.deps import PaginationDep, PermissionChecker

router = APIRouter()


@router.get(
    "/",
    response_model=PaginatedResponse[RoleRead],
    summary="获取角色分页列表",
    dependencies=[Depends(PermissionChecker("system:role:list"))],
)
async def get_roles_list(
    pagination: PaginationDep,
) -> PaginatedResponse[RoleRead]:
    """
    获取带有分页信息的角色列表。
    需要 `system:role:list` 权限。
    """
    roles, total = await role_service.get_active_paginated(
        page=pagination["page"],
        page_size=pagination["page_size"],
        order_by=["sort_order", "-created_at"],
    )
    return PaginatedResponse(
        total=total,
        page=pagination["page"],
        page_size=pagination["page_size"],
        data=[RoleRead.model_validate(role, from_attributes=True) for role in roles],
    )


@router.post(
    "/",
    response_model=RoleRead,
    summary="创建新角色",
    dependencies=[Depends(PermissionChecker("system:role:create"))],
)
async def create_role(
    role_in: RoleCreate,
) -> RoleRead:
    """
    创建一个新角色，并可以同时关联权限。
    需要 `system:role:create` 权限。
    """
    new_role = await role_service.create_role(role_in)
    return RoleRead.model_validate(new_role, from_attributes=True)


@router.get(
    "/{role_id}",
    response_model=RoleRead,
    summary="获取指定角色信息",
    dependencies=[Depends(PermissionChecker("system:role:view"))],
)
async def get_role_by_id(role_id: int) -> RoleRead:
    """
    获取指定ID的角色详细信息，包含其关联的权限。
    需要 `system:role:view` 权限。
    """
    role_model = await role_service.dao.get_by_id_with_prefetch(role_id, "permissions")
    if not role_model:
        raise HTTPException(status_code=404, detail="角色不存在")
    role = cast(Role, role_model)
    if role.is_deleted:
        raise HTTPException(status_code=404, detail="角色不存在或已被删除")
    return RoleRead.model_validate(role, from_attributes=True)


@router.put(
    "/{role_id}",
    response_model=RoleRead,
    summary="更新角色信息",
    dependencies=[Depends(PermissionChecker("system:role:update"))],
)
async def update_role(
    role_id: int,
    role_in: RoleUpdate,
) -> RoleRead:
    """
    更新指定ID的角色信息，并可以同时更新其关联的权限。
    需要 `system:role:update` 权限。
    """
    updated_role = await role_service.update_role(role_id, role_in)
    return RoleRead.model_validate(updated_role, from_attributes=True)


@router.delete(
    "/{role_id}",
    status_code=204,
    summary="删除角色",
    dependencies=[Depends(PermissionChecker("system:role:delete"))],
)
async def delete_role(role_id: int) -> None:
    """
    软删除指定ID的角色。
    需要 `system:role:delete` 权限。
    """
    success = await role_service.soft_delete(role_id)
    if not success:
        raise HTTPException(status_code=404, detail="角色不存在或删除失败")
    return None
